package com.example.cinema.request;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.example.cinema.UserAttribute;
import com.example.cinema.bindingdata.ShortBindingData;
import com.example.cinema.bindingdata.UserVideoInfoData;
import com.example.cinema.bindingdata.VideoData;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RequestSend {

    /**
     * 用户提交评价
     *
     * @param vid
     * @param uid
     * @param text
     * @return
     */
    private static final MediaType FORM_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    private String URL;
    private Context context;

    public RequestSend(Context context) {
        try {
            if(context==null)
            {
                return;
            }
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            URL = info.metaData.getString("url");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发布动态
     *
     * @param title   标题
     * @param centext 内容
     * @param imgurl  图片地址
     * @param type    动态类型
     */
    public boolean CircleSend(String type, String title, String centext, List<File> imgurl, String uid) {
        boolean isbool = false;
        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder multipart = new MultipartBody.Builder();//创建一个多部分生成器
        multipart.addFormDataPart("title", title);//添加参数
        multipart.addFormDataPart("centext", centext);
        multipart.addFormDataPart("type", type);
        multipart.addFormDataPart("uid", uid);

        for (int i = 0; i < imgurl.size(); i++) {
            MediaType types = MediaType.parse("image/*");//媒体类型
            File fil = imgurl.get(i);//获取文件File
            RequestBody requestBody = RequestBody.Companion.create(fil, types);//创建请求体
            multipart.addFormDataPart("image", "image", requestBody);//添加请求数据到多部分文件
        }
        //创建请求
        Request requestBody = new Request.Builder().url(URL + "/us/upcircle").post(multipart.build()).build();
        //发起请求
        try {
            Response response = client.newCall(requestBody).execute();
            String bod = response.body().string();
            if (bod.equals("200")) {
                isbool = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isbool;
    }

    /**
     * 帖子点赞
     *
     * @param mdid 帖子ID
     * @param uid  用户ID
     */
    public boolean MoodZan(String mdid, String uid, UserAttribute attr) {
        boolean is = false;
        OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {

            }

            @NotNull
            @Override
            public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                List<Cookie> list = new ArrayList<>();
                Cookie ck = new Cookie.Builder()
                        .name("token")
                        .value(attr.getToken())
                        .path("/us/")
                        .hostOnlyDomain(httpUrl.host())
                        .build();
                Cookie cka = new Cookie.Builder()
                        .name("uid")
                        .value(attr.getUID())
                        .path("/us/")
                        .hostOnlyDomain(httpUrl.host())
                        .build();
                list.add(ck);
                list.add(cka);
                return list;
            }
        }).build();
        FormBody formBody = new FormBody.Builder().add("mid", mdid).add("uid", uid).build();
        Request request = new Request.Builder().post(formBody).url(URL + "/us/moodzan").build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            if (bod.equals("200")) {
                is = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

    public boolean SendAssess(String vid, String uid, String text) {
        boolean b = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = null;
        String param = "vid=" + vid + "&texts=" + text + "&uid=" + uid;

        RequestBody requestBody = RequestBody.create(FORM_TYPE, param);

        Request request = new Request.Builder().post(requestBody).url(URL + "/us/usersendase").build();
        try {
            Response response = client.newCall(request).execute();
            String retul = response.body().string();
            Log.i("ttttt", retul);
            if (retul.equals("200")) {
                b = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }

    /**
     * 用户评语点赞
     *
     * @param vid
     * @param uid
     * @return
     */
    public boolean SendUserZan(String vid, String uid) {
        boolean ss = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder().add("uid", uid).add("vid", vid).build();
        Request request = new Request.Builder().url(URL + "/us/usvdzan").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("TTTT", bod);
            if (bod.equals("200")) {
                ss = true;
            } else {
                ss = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ss;
    }

    /**
     * 视频点赞
     *
     * @param vid 视频ID
     * @return
     */
    public boolean SendVideoZan(String vid) {
        boolean boo = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder().add("vid", vid).build();
        Request request = new Request.Builder().url(URL + "/us/videzan").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("JJJ", bod);
            if (bod.equals("200")) {
                boo = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return boo;
    }

    /**
     * Vip判断
     *
     * @param uid 用户ID
     * @return
     */
    public boolean VipCheck(String uid) {
        boolean boo = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder().add("uid", uid).build();
        Request request = new Request.Builder().url(URL + "/us/vipcheck").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String ss = response.body().string();
            Log.i("HHHDS",ss);
            if (ss.equals("200")) {
                boo = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return boo;
    }


    /**
     * 发送登录请求
     */
    public boolean UserLong(String name, String pswd, UserAttribute attribute,String id) {
        boolean bool = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder().add("username", name).add("userpswd", pswd).add("device",id).build();
        Request request = new Request.Builder().url(URL + "/com/usersing").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("AAAADE", bod);
            Headers headers = response.headers();//获取请求头信息
            String token = headers.get("Set-Cookie");
            JSONObject jo = new JSONObject(bod);
            int code = jo.getInt("code");
            Log.i("AAAADE", code+"");
            if (token != null) {
                JSONObject ifno = jo.getJSONObject("data");
                String[] ckv = token.split("=");
                attribute.setToken(ckv[1]);
                attribute.setUname(name);
                attribute.setUID(ifno.getString("usersid"));
                attribute.setUimage(ifno.getString("userimg"));
                attribute.setFans(Integer.valueOf(ifno.getString("userfans")));
                attribute.setFollow(Integer.valueOf(ifno.getString("userfollow")));
                attribute.setFree(Integer.valueOf(ifno.getString("userfree")));
                attribute.setLove(Integer.valueOf(ifno.getString("userlove")));
                attribute.setState(Integer.valueOf(ifno.getString("userstate")));
                attribute.setUalias(ifno.getString("useralias"));
                attribute.setUserworks(ifno.getInt("userworks"));
                String tm = null;
                if(!ifno.isNull("usertime"))
                {
                    tm = ifno.getString("usertime");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long tt;
                if (tm!=null) {
                    tt = sdf.parse(tm).getTime();
                } else {
                    tt = System.currentTimeMillis();
                }

                Log.i("KKKSD",tt+"");

                long to = new Date().getTime();
                Log.i("KKKSD",tt+"");
                if (tt > to) {
                    Log.i("KKKSD",tt+"VIP");
                    attribute.setViptime(tm + "到期");
                    attribute.setVipbool(true);
                } else {
                    Log.i("KKKSD",tt+"非VIP");
                    attribute.setViptime("您还不是VIP哦");
                    attribute.setVipbool(false);
                }
                if(ifno.isNull("usertime"))
                {
                    tm = sdf.format(new Date());
                }
                attribute.setViptime(tm);
            }
            if (code == 200) {
                bool = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return bool;
    }

    /**
     * 发送改密
     *
     * @param pswda     新密码
     * @param attribute 全局变量
     * @return
     */
    public boolean ReqUserPaswd(String pswda, UserAttribute attribute, String code) {
        boolean abool = false;
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {

                    }

                    @NotNull
                    @Override
                    public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                        List<Cookie> list = new ArrayList<>();
                        Cookie cookiea = new Cookie.Builder()
                                .name("uid").value(attribute.getUID())
                                .name("token").value(attribute.getToken())
                                .hostOnlyDomain(httpUrl.host())
                                .build();
                        list.add(cookiea);
                        return list;
                    }
                }).build();
        FormBody formBody = new FormBody.Builder().add("name", attribute.getUname())
                .add("pswd", pswda)
                .add("code", code)
                .build();
        Request request = new Request.Builder().url(URL + "/us/modify").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            JSONObject object = new JSONObject(bod);
            int c = object.getInt("code");
            if (c == 0) {
                abool = true;
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return abool;
    }

    /**
     * 改密发送验证码
     *
     * @param phone     手机号
     * @param attribute 全局变量
     * @return
     */
    public boolean SendPhoneCode(String phone, UserAttribute attribute) {
        boolean abool = false;
        OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {

            }

            @NotNull
            @Override
            public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                List<Cookie> list = new ArrayList<>();
                Cookie cookiea = new Cookie.Builder()
                        .name("uid").value(attribute.getUID())
                        .name("token").value(attribute.getToken())
                        .hostOnlyDomain(httpUrl.host())
                        .build();
                list.add(cookiea);
                return list;
            }
        }).build();
        FormBody formBody = new FormBody.Builder().add("phone", phone).build();
        Request request = new Request.Builder().post(formBody).url(URL + "/us/sendcode").build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("PPPPP", bod);
            JSONObject jo = new JSONObject(bod);
            int code = jo.getInt("code");
            if (code == 0) {
                abool = true;
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return abool;
    }


    /**
     * 发送注册验证码
     *
     * @param phone
     * @return
     */
    public boolean SendPostCode(String phone) {
        boolean bool = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder().add("phond", phone).build();
        Request request = new Request.Builder().url(URL + "/com/senmsg").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            if (bod.equals("200")) {
                bool = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * 发送注册
     *
     * @param phone 手机号
     * @param pswd  密码
     * @param code  验证码
     * @param id    设备码
     * @return
     */
    public boolean ReqUserPost(String phone, String pswd, String code, String id) {
        boolean boo = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder()
                .add("username", phone)
                .add("userpswd", pswd)
                .add("code", code)
                .add("pid", id)
                .build();
        Request request = new Request.Builder().url(URL + "/com/postuser").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String cod = response.body().string();
            Log.i("HHHHF",cod);
            if (cod.equals("200")) {
                boo = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return boo;
    }


    /**
     * 发布帖子评价
     *
     * @param mid
     * @param attribute
     * @param text
     * @return
     */
    public boolean SendMoodAssess(String mid, UserAttribute attribute, String text) {
        boolean bool = false;

        OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {

            }

            @NotNull
            @Override
            public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                List<Cookie> list = new ArrayList<>();
                Cookie cookie = new Cookie.Builder()
                        .hostOnlyDomain(httpUrl.host())
                        .name("token")
                        .path("/us/")
                        .value(attribute.getToken()).build();
                Cookie cookie1 = new Cookie.Builder()
                        .hostOnlyDomain(httpUrl.host())
                        .name("uid")
                        .value(attribute.getUID())
                        .path("/us/")
                        .build();
                list.add(cookie);
                list.add(cookie1);
                return list;
            }
        }).build();
        String param = "uid=" + attribute.getUID() + "&mid=" + mid + "&text=" + text;
        RequestBody requestBody = RequestBody.create(FORM_TYPE, param);
        Request request = new Request.Builder().post(requestBody).url(URL + "/us/senmoodpj").build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("RRRR", bod);
            if (bod.equals("200")) {
                bool = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * 帖子回帖点赞
     *
     * @param uid
     * @param tid
     * @return
     */
    public boolean UserMoodZan(String uid, String tid) {
        boolean ss = false;
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder().add("tid", tid).add("uid", uid).build();
        Request request = new Request.Builder().url(URL + "/us/mooduserzan").post(formBody).build();
        try {
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("TTTT", bod);
            if (bod.equals("200")) {
                ss = true;
            } else {
                ss = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ss;
    }


    /**
     * 关注
     *
     * @param uid  用户ID
     * @param uid1 被关注用户ID
     * @return
     */
    public boolean Follow(String uid, String uid1, UserAttribute attribute) {
        boolean ass = false;
        try {
            OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
                }

                @NotNull
                @Override
                public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                    List<Cookie> list = new ArrayList<>();
                    Cookie cookiea = new Cookie.Builder()
                            .name("token").value(attribute.getToken())
                            .hostOnlyDomain(httpUrl.host()).build();
                    Cookie cookieb = new Cookie.Builder()
                            .name("uid").value(attribute.getUID())
                            .hostOnlyDomain(httpUrl.host()).build();
                    list.add(cookiea);
                    list.add(cookieb);
                    return list;
                }
            }).build();
            FormBody formBody = new FormBody.Builder()
                    .add("uid", uid).add("follow", uid1).build();
            Request request = new Request.Builder().url(URL + "/us/follow").post(formBody).build();
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("BBBB", bod);
            if (bod.equals("200")) {
                ass = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ass;
    }


    /**
     * 卡密充值
     *
     * @param cart
     * @param attribute
     * @return
     */
    public boolean CartChong(String cart, UserAttribute attribute) {
        boolean ab = false;
        try {
            OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {

                }

                @NotNull
                @Override
                public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                    List<Cookie> list = new ArrayList<>();
                    Cookie cookiea = new Cookie.Builder()
                            .name("token").value(attribute.getToken())
                            .hostOnlyDomain(httpUrl.host()).build();
                    Cookie cookieb = new Cookie.Builder()
                            .name("uid").value(attribute.getUID())
                            .hostOnlyDomain(httpUrl.host()).build();
                    list.add(cookiea);
                    list.add(cookieb);
                    return list;
                }
            }).build();
            FormBody body = new FormBody.Builder().add("cart", cart).add("uid", attribute.getUID()).build();
            Request request = new Request.Builder().post(body).url(URL + "/us/cartecharge").build();
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            if (bod.equals("200")) {
                ab = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ab;
    }


    /**
     * 获取指定用户UID的视频列表
     */
    public JSONObject GetUidList(String uid, int p, int l) {
        JSONObject oB = null;
        try {
            OkHttpClient client = new OkHttpClient();
            FormBody formBody = new FormBody.Builder().add("page", p + "").add("limit", l + "").add("uid", uid).build();
            Request request = new Request.Builder().url(URL + "/com/getuidlist").post(formBody).build();
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("BBBB", bod);
            oB = new JSONObject(bod);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return oB;
    }


    /**
     * 查询是否已关注
     */
    public boolean isFollow(String uid, String fuid, UserAttribute attribute) {
        boolean abool = false;
        try {

            Log.i("MMMSS", uid);
            Log.i("MMMSS", fuid);
            OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {

                }

                @NotNull
                @Override
                public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                    List<Cookie> list = new ArrayList<>();
                    Cookie cookiea = new Cookie.Builder().name("token").value(attribute.getToken()).hostOnlyDomain(httpUrl.host()).path("/us/").build();
                    Cookie cookieb = new Cookie.Builder().name("uid").value(attribute.getUID()).hostOnlyDomain(httpUrl.host()).path("/us/").build();
                    list.add(cookiea);
                    list.add(cookieb);
                    return list;
                }
            }).build();
            FormBody formBody = new FormBody.Builder().add("uid", uid).add("fuid", fuid).build();
            Request request = new Request.Builder().post(formBody).url(URL + "/us/isfollow").build();
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            Log.i("IIII", bod);
            if (bod.equals("200")) {
                abool = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return abool;
    }


    /**
     * 找回密码
     */
    public boolean Retrieve(String phone) {
        boolean ab = false;
        try {
            OkHttpClient client = new OkHttpClient();
            FormBody formBody = new FormBody.Builder().add("phone", phone).build();
            Request request = new Request.Builder().url(URL + "/com/retrieve").post(formBody).build();
            Response response = client.newCall(request).execute();
            String bod = response.body().string();
            if(bod.equals("200"))
            {
                ab = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ab;
    }

}
